package com.hk.springdatajpa;

import com.hk.springdatajpa.dao.CarRepository;
import com.hk.springdatajpa.dao.CustomerRepository;
import com.hk.springdatajpa.entity.Car;
import com.hk.springdatajpa.entity.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author by 何坤
 * @Classname JpaTest02
 * @Description TODO
 * @Date 2019/9/27 10:30
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaTest02 {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private CarRepository carRepository;

    @Test
    public void testOneToMany(){
        Optional<Customer> byId = customerRepository.findById(5L);
        if (byId.isPresent()){
            System.out.println(byId.get());
        }else {
            System.out.println("没有找到信息");
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void testAdd(){
        Customer customer = new Customer();
        customer.setName("何坤");
        customer.setAddress("四川省成都市");
        customer.setIndustry("IT");
        customer.setPhone("13281896139");
        customer.setSource("文思海辉");
        customer.setLevel("VIP1");

        Car car = new Car();
        car.setBrand("丰田");
        car.setColor("黑色");
        car.setLicence("川RW1809");
        car.setType("SUV");

        customer.getCars().add(car);
        car.setCustomer(customer);

        customerRepository.save(customer);
        carRepository.save(car);
    }

    /**
     * 级联添加
     * @param
     * @return void
     * @date 2019/9/27 14:21
     * @author 何坤
     */
    @Test
    @Transactional
    @Rollback(false)
    public void testCascadeAdd(){
        Customer customer = new Customer();
        customer.setName("杜霞");
        customer.setAddress("四川省成都市");
        customer.setIndustry("美容");
        customer.setPhone("13281896139");
        customer.setSource("芳香世家");
        customer.setLevel("VIP2");

        Car car = new Car();
        car.setBrand("宝马");
        car.setColor("黑色");
        car.setLicence("川RW7468");
        car.setType("轿车");

        car.setCustomer(customer);
        customer.getCars().add(car);

        customerRepository.save(customer);
    }


    /**
     * 测试级联删除
     * @param
     * @return void
     * @date 2019/9/27 14:33
     * @author 何坤
     */
    @Test
    @Transactional
    @Rollback(false)
    public void testCascadeRemove(){
        Optional<Customer> byId = customerRepository.findById(5L);
        customerRepository.deleteById(byId.get().getId());
    }

}
